/*
 * Copyright 2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
function fetchComments(uri) {
	var base = $("base").attr("href");

	// create editor on "comment-box" textarea but only if it exists
	if ($('#comment-box').length) {
		new wysihtml5.Editor("comment-box", {
			toolbar : "toolbar",
			parserRules : wysihtml5ParserRules
		});

		$('#respond').submit(handleSubmit);
	}

	// fetch the initial set of comments
	$.ajax({
		url : 'fetchComments.do?start=0&uri=' + uri,
		type : "get",
		success : function(result) {
			$('#loadingDiv').hide();
			var postsList = $('#content');
			postsList.replaceWith(result);

			//$('.admin').html("<b>Delete</b>");
		},
		failure : function(error) {
			//alert(error);
			$('#loadingDiv').hide();
		}
	});

	// handle comment paging
	$('body').on('click', '.nav', function(e) {
		e.preventDefault();
		var target = e.currentTarget;

		$.ajax({
			url : target,
			type : "get",
			success : function(result) {
				var postsList = $('#content');
				postsList.replaceWith(result);
			}
		});
	});
}

function handleSubmit() {
	var form = $(this);
	var data = {
		"comment" : form.find('#comment-box').val(),
		"id" : form.find('#comment_post_ID').val()
	};

	postComment(data);

	return false;
}

function postComment(data) {
	var base = $("base").attr("href");

	$.ajax({
		type : 'post',
		url :  'postComment.do',
		data : data,
		headers : {
			'X-Requested-With' : 'XMLHttpRequest'
		},
		success : postSuccess,
		error : postError
	});
}

function postSuccess(data, textStatus, jqXHR) {
	$('#respond').get(0).reset();
	displayComment(data);
}

function displayComment(comment) {
	var commentHtml = toHtml(comment);
	var commentEl = $(commentHtml);
	commentEl.hide();
	var postsList = $('#posts-list');
	postsList.addClass('has-comments');
	postsList.append(commentEl);
	commentEl.slideDown();
}

function toHtml(comment) {
	var html = '<li><div class="row"><div class="three columns">'
			+ '<label>Posted by</label>' + comment.author + ' ' + comment.date
			+ '</div><div class="nine columns">' + '<div class="newpost">'
			+ comment.comment + '</div></div></div></li>';

	return html;
}

function postError(jqXHR, textStatus, errorThrown) {
	alert('posting error ' + textStatus);
}